const fs = require('fs');
const path = require('path');
const NodeRSA = require('node-rsa'); //引入node-rsa 模块 
const { priKeyPath, pubKeyPath } = require('../../');





const RSA = require('node-rsa');

function createKey() {
    // 生成一个新的 RSA 密钥对，长度为 512 位
    const key = new RSA({ b: 512 });

    key.setOptions({ encryptionScheme: 'pkcs1' }) // 设置加密方案为 PKCS1

    // 输出公钥和私钥
    let public_key = key.exportKey('pkcs8-public')//公钥,
    let private_key = key.exportKey('pkcs8-private') //私钥
    fs.writeFileSync(priKeyPath, private_key);  //写入文件
    fs.writeFileSync(pubKeyPath, public_key);   //写入文件
}

function encrypt(plain) {  //加密
    let public_key = fs.readFileSync(pubKeyPath, 'utf8');   //读取公钥
    const nodersa = new NodeRSA(public_key);                //实例化
    nodersa.setOptions({ encryptionScheme: 'pkcs1' });      //设置加密方案
    const encrypted = nodersa.encrypt(plain, 'base64');     //加密
    return encrypted;
}
function decrypt(cipher) { //解密
    let private_key = fs.readFileSync(priKeyPath, 'utf8'); //私钥
    let prikey = new NodeRSA(private_key);                 //实例化
    prikey.setOptions({ encryptionScheme: 'pkcs1' });      //设置加密方案
    return prikey.decrypt(cipher, 'utf8')                  //解密
}





module.exports = {
    createKey, //生成公钥私钥
    encrypt,  //加密
    decrypt,  //解密

};